package com.sojson.config.task.bean;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

import org.springframework.core.task.TaskDecorator;

import lombok.extern.slf4j.Slf4j;

/**
 * 线程装饰器,类似切面
 *
 * @author liu
 * @date 2022-01-17
 */
@Slf4j
public class CustomTaskDecorator implements TaskDecorator {

    private final List<TdHandler<?>> HANDLERS = new ArrayList<>();

    public CustomTaskDecorator(List<TdHandler<?>> handlers) {
        addHandler(handlers);
    }

    @Override
    public Runnable decorate(Runnable runnable) {
        int size = HANDLERS.size();

        List<Object> param = new ArrayList<>(size);
        for (int i = 0; i < size; i++) {
            param.add(HANDLERS.get(i).prefix());
        }

        return () -> {
            try {
                for (int i = 0; i < size; i++) {
                    HANDLERS.get(i).runByThread(param.get(i));
                }
                runnable.run();
            } finally {
                for (int i = size - 1; i > -1; i--) {
                    try {
                        HANDLERS.get(i).finallys();
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    }
                }
            }
        };
    }

    public void addHandler(TdHandler<?> handler) {
        HANDLERS.add(handler);
        sortHandler();
    }

    public void addHandler(List<TdHandler<?>> handlers) {
        HANDLERS.addAll(handlers);
        sortHandler();
    }

    public void sortHandler() {
        HANDLERS.sort(new Comparator<TdHandler<?>>() {
            @Override
            public int compare(TdHandler<?> o1, TdHandler<?> o2) {
                return o1.getSort() - o2.getSort();
            }
        });
    }

}